<template>
  <div class="font-inter bg-neutral-100 text-neutral-700">
    <div class="mx-auto px-4 py-1 max-w-6xl">
      <!-- 页面标题 -->
      <header class="mb-4">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-700 mb-2">数据字典选项管理</h1>
        <p class="text-neutral-500">管理数据字典的各类选项，如颜色、尺码、材质、订单状态等</p>
      </header>

      <!-- 主要内容区 -->
      <div class="bg-white rounded-xl shadow-md overflow-hidden" style="height: 450px">
        <div class="flex flex-col md:flex-row">
          <!-- 左侧选项类目 -->
          <div class="w-full md:w-1/3 border-b md:border-b-0 md:border-r border-neutral-200">
            <div class="p-4 border-b border-neutral-200 flex justify-between items-center">
              <h2 class="font-semibold text-lg">选项类目</h2>
              <button
                id="add-category-btn"
                class="bg-primary hover:bg-primary/90 text-white px-3 py-1.5 rounded-lg text-sm flex items-center transition-bg"
                @click="openAddCategoryModal"
              >
                <el-icon><Plus /></el-icon>&nbsp; 添加类目
              </button>
            </div>

            <div id="categories-list" class="h-[calc(60vh-10rem)] overflow-y-auto scrollbar-hide">
              <!-- 选项类目列表将通过JavaScript动态生成 -->
              <div v-if="productSpecs.length === 0" class="p-4 text-center text-neutral-400">
                <i class="fa fa-info-circle mb-2"></i>
                <p>暂无选项类目，请添加</p>
              </div>

              <div
                v-for="category in productSpecs"
                :key="category.dict_type"
                @click="selectCategory(category.dict_type)"
                @contextmenu="handleCategoryContextMenu($event, category.dict_type)"
                :class="[
                  'p-3 flex justify-between items-center cursor-pointer transition-bg',
                  selectedCategoryId === category.id ? 'bg-primary/10 border-l-4 border-primary' : 'hover:bg-neutral-100'
                ]"
              >
                <span :class="selectedCategoryId === category.id ? 'font-medium text-primary' : 'font-medium text-neutral-700'">
                  {{ category.dict_type }}
                </span>
                <span class="text-xs text-neutral-500">{{ category.total_num }}个选项</span>
              </div>
            </div>
          </div>

          <!-- 右侧选项值 -->
          <div class="w-full md:w-2/3">
            <div
              id="no-selection"
              class="h-[calc(70vh-6rem)] flex flex-col items-center justify-center text-neutral-400"
              :class="{ hidden: selectedCategoryId }"
            >
              <i class="fa fa-folder-open-o text-5xl mb-4"></i>
              <p class="text-lg">请选择一个选项类目</p>
              <p class="text-sm mt-2">或点击左侧"添加类目"按钮创建新类目</p>
            </div>

            <div id="option-values-container" :class="{ hidden: !selectedCategoryId }">
              <div class="p-4 border-b border-neutral-200 flex justify-between items-center">
                <h2 id="current-category-name" class="font-semibold text-lg">{{ selectedCategoryId }}</h2>
              </div>

              <div id="option-values-list" class="p-4 min-h-[calc(60vh-12rem)]">
                <!-- 选项值列表将通过JavaScript动态生成 -->
                <div id="option-buttons" class="flex flex-wrap">
                  <div v-if="currentCategory.length === 0" class="w-full p-4 text-center text-neutral-400">
                    <i class="fa fa-info-circle mb-2"></i>
                    <p>该类目下暂无选项值，请添加</p>
                  </div>

                  <button
                    v-for="value in currentCategory"
                    :key="value.id"
                    class="option-btn"
                    @click="startEditingValue(value.id)"
                  >
                    {{ value.dict_value }}
                    <span class="delete-btn text-danger" @click.stop="deleteValue(value.id)">
                      <el-icon><CircleCloseFilled /></el-icon>
                    </span>
                  </button>
                </div>
                <button id="add-value-btn" class="add-option-btn mt-2" @click="openAddValueModal">
                  <i class="fa fa-plus mr-1"></i> 添加选项
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加类目模态框 -->
    <div
      id="add-category-modal"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      :class="{ hidden: !addCategoryModalVisible }"
    >
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
        <div class="flex justify-between items-center mb-4">
          <h3 class="font-semibold text-lg">添加选项类目</h3>
          <button id="close-category-modal" class="text-neutral-400 hover:text-neutral-700" @click="closeAddCategoryModal">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="mb-4">
          <label for="category-name" class="block text-sm font-medium text-neutral-700 mb-1">类目名称</label>
          <input
            type="text"
            id="category-name"
            class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
            placeholder="请输入类目名称"
            v-model="categoryName"
          />
        </div>
        <div class="flex justify-end space-x-3">
          <button
            id="cancel-add-category"
            class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-100 transition-bg"
            @click="closeAddCategoryModal"
          >
            取消
          </button>
          <button
            id="confirm-add-category"
            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-bg"
            @click="confirmAddCategory"
          >
            确认添加
          </button>
        </div>
      </div>
    </div>

    <!-- 添加选项值模态框 -->
    <div
      id="add-value-modal"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      :class="{ hidden: !addValueModalVisible }"
    >
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
        <div class="flex justify-between items-center mb-4">
          <h3 class="font-semibold text-lg">添加选项值</h3>
          <button id="close-value-modal" class="text-neutral-400 hover:text-neutral-700" @click="closeAddValueModal">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="mb-4">
          <label for="value-name" class="block text-sm font-medium text-neutral-700 mb-1">选项值</label>
          <input
            type="text"
            id="value-name"
            class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
            placeholder="请输入选项值"
            v-model="valueName"
          />
        </div>
        <div class="flex justify-end space-x-3">
          <button
            id="cancel-add-value"
            class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-100 transition-bg"
            @click="closeAddValueModal"
          >
            取消
          </button>
          <button
            id="confirm-add-value"
            class="px-4 py-2 bg-secondary text-white rounded-lg hover:bg-secondary/90 transition-bg"
            @click="confirmAddValue"
          >
            确认添加
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑选项值模态框 -->
    <div
      id="edit-value-modal"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-50"
      :class="{ hidden: !editValueModalVisible }"
    >
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6 transform transition-all">
        <div class="flex justify-between items-center mb-4">
          <h3 class="font-semibold text-lg">编辑选项值</h3>
          <button id="close-edit-modal" class="text-neutral-400 hover:text-neutral-700" @click="closeEditModal">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="mb-4">
          <label for="edit-value-name" class="block text-sm font-medium text-neutral-700 mb-1">选项值</label>
          <input
            type="text"
            id="edit-value-name"
            class="w-full px-3 py-2 border border-neutral-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary outline-none transition-all"
            placeholder="请输入选项值"
            v-model="editValueName"
          />
        </div>
        <div class="flex justify-end space-x-3">
          <button
            id="cancel-edit-value"
            class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-100 transition-bg"
            @click="closeEditModal"
          >
            取消
          </button>
          <button
            id="confirm-edit-value"
            class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-bg"
            @click="confirmEditValue"
          >
            确认修改
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { addDict, addDictSelection, delteDictSelection, getDictList, getDictSelect } from "@/api/modules/dict.ts";
import { ElMessage, ElMessageBox } from "element-plus";
// 示例数据
const productSpecs = ref([
  {
    id: 1,
    name: "尺码",
    values: [
      { id: 101, value: "S" },
      { id: 102, value: "M" },
      { id: 103, value: "X" },
      { id: 104, value: "XL" }
    ]
  },
  {
    id: 2,
    name: "颜色",
    values: [
      { id: 201, value: "红色" },
      { id: 202, value: "绿色" },
      { id: 203, value: "灰色" }
    ]
  }
]);

// 当前选中的类目ID
const selectedCategoryId = ref(null);
// 当前编辑的选项值ID
const editingValueId = ref(null);

// 模态框状态
const addCategoryModalVisible = ref(false);
const addValueModalVisible = ref(false);
const editValueModalVisible = ref(false);

// 表单数据
const categoryName = ref("");
const valueName = ref("");
const editValueName = ref("");

// 计算属性：当前选中的类目
const currentCategory = ref([]);

// 打开添加类目模态框
const openAddCategoryModal = () => {
  addCategoryModalVisible.value = true;
  categoryName.value = "";

  // 添加动画效果
  setTimeout(() => {
    const modal = document.getElementById("add-category-modal");
    if (modal) {
      modal.querySelector("div").classList.add("scale-100");
      modal.querySelector("div").classList.remove("scale-95");
    }
  }, 10);

  // 聚焦输入框
  setTimeout(() => {
    const input = document.getElementById("category-name");
    if (input) input.focus();
  }, 100);
};

// 关闭添加类目模态框
const closeAddCategoryModal = () => {
  const modal = document.getElementById("add-category-modal");
  if (modal) {
    modal.querySelector("div").classList.remove("scale-100");
    modal.querySelector("div").classList.add("scale-95");

    setTimeout(() => {
      addCategoryModalVisible.value = false;
    }, 200);
  }
};

// 确认添加类目
const confirmAddCategory = async () => {
  const name = categoryName.value.trim();

  if (!name) {
    ElMessage.error("请输入类目名称");
    return;
  }

  /*
  // 检查是否已存在同名类目
  if (productSpecs.value.some(c => c.name.toLowerCase() === name.toLowerCase())) {
    alert("该类目名称已存在");
    return;
  }
*/

  /*
  const newId = productSpecs.value.length > 0 ? Math.max(...productSpecs.value.map(c => c.id)) + 1 : 1;

*/
  productSpecs.value.push({
    dict_type: name,
    total_num: 0
  });
  let res = await addDict({
    dict_type: name,
    type: "1"
  });
  if (res.code === 200) {
    ElMessage.success("添加成功");
    categoryName.value = "";
    closeAddCategoryModal();
  }

  // selectCategory(newId);
};

// 打开添加选项值模态框
const openAddValueModal = () => {
  if (selectedCategoryId.value) {
    addValueModalVisible.value = true;
    valueName.value = "";

    // 添加动画效果
    setTimeout(() => {
      const modal = document.getElementById("add-value-modal");
      if (modal) {
        modal.querySelector("div").classList.add("scale-100");
        modal.querySelector("div").classList.remove("scale-95");
      }
    }, 10);

    // 聚焦输入框
    setTimeout(() => {
      const input = document.getElementById("value-name");
      if (input) input.focus();
    }, 100);
  }
};

// 关闭添加选项值模态框
const closeAddValueModal = () => {
  const modal = document.getElementById("add-value-modal");
  if (modal) {
    modal.querySelector("div").classList.remove("scale-100");
    modal.querySelector("div").classList.add("scale-95");

    setTimeout(() => {
      addValueModalVisible.value = false;
    }, 200);
  }
};

// 确认添加选项值
const confirmAddValue = async () => {
  const name = valueName.value.trim();

  if (!name) {
    ElMessage.info("请输入选项值");
    return;
  }

  const category = productSpecs.value.find(c => c.dict_type === selectedCategoryId.value);

  if (!category) {
    ElMessage.warning("请先选择一个类目");
    closeAddValueModal();
    return;
  }

  // // 检查是否已存在同名选项值
  // if (category.values.some(v => v.value.toLowerCase() === name.toLowerCase())) {
  //   alert("该选项值已存在");
  //   return;
  // }

  // const newId = category.length > 0 ? Math.max(...category.map(v => v.id)) + 1 : category.id * 100 + 1;
  let params = {
    dict_type: category.dict_type,
    dict_code: name,
    dict_value: name
  };
  let res = await addDictSelection(params);
  if (res.code === 200) {
    currentCategory.value.push(params);
    valueName.value = "";
    closeAddValueModal();
    ElMessage.info("添加成功");
  }
};

// 开始编辑选项值
const startEditingValue = id => {
  const category = productSpecs.value.find(c => c.id === selectedCategoryId.value);

  if (!category) return;

  const value = category.find(v => v.id === id);

  if (!value) return;

  editingValueId.value = id;
  editValueName.value = value.value;
  editValueModalVisible.value = true;

  // 添加动画效果
  setTimeout(() => {
    const modal = document.getElementById("edit-value-modal");
    if (modal) {
      modal.querySelector("div").classList.add("scale-100");
      modal.querySelector("div").classList.remove("scale-95");
    }
  }, 10);

  // 聚焦输入框
  setTimeout(() => {
    const input = document.getElementById("edit-value-name");
    if (input) input.focus();
  }, 100);
};

// 关闭编辑选项值模态框
const closeEditModal = () => {
  const modal = document.getElementById("edit-value-modal");
  if (modal) {
    modal.querySelector("div").classList.remove("scale-100");
    modal.querySelector("div").classList.add("scale-95");

    setTimeout(() => {
      editValueModalVisible.value = false;
    }, 200);
  }
};

// 确认编辑选项值
const confirmEditValue = () => {
  if (!editingValueId.value) return;

  const name = editValueName.value.trim();

  if (!name) {
    ElMessage.warning("请输入选项值");
    return;
  }

  const category = productSpecs.value.find(c => c.id === selectedCategoryId.value);

  if (!category) {
    ElMessage.warning("请先选择一个类目");
    closeEditModal();
    return;
  }

  // 检查是否已存在同名选项值（排除当前编辑的选项值）
  if (category.values.some(v => v.id !== editingValueId.value && v.value.toLowerCase() === name.toLowerCase())) {
    ElMessage.warning("该选项值已存在");
    return;
  }

  const valueIndex = category.values.findIndex(v => v.id === editingValueId.value);

  if (valueIndex !== -1) {
    category.values[valueIndex].value = name;
  }

  editingValueId.value = null;
  editValueName.value = "";
  closeEditModal();
};

// 删除选项值
const deleteValue = async id => {
  try {
    // 只有用户点击确认时才继续执行删除
    await ElMessageBox.confirm("确定要删除这个选项值吗？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    });

    // 调用删除接口
    let res = await delteDictSelection({ id: id });

    if (res.code === 200) {
      ElMessage.success("删除成功");
      // 从当前类目中移除该选项值
      currentCategory.value = currentCategory.value.filter(v => v.id !== id);
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    // 用户取消操作或其他错误
    if (error !== "cancel") {
      ElMessage.error("删除过程中发生错误");
    }
  }
};

// 选择类目
const selectCategory = async id => {
  selectedCategoryId.value = id;
  let res = await getDictSelect({ dict_type: id });
  currentCategory.value = res.data.list;
};

// 处理类目右键菜单（占位函数，原代码未实现）
const handleCategoryContextMenu = (e, id) => {
  e.preventDefault();
  // 这里可以实现右键菜单功能
  // 例如：
  deleteCategory(id);
};

// 初始化页面
onMounted(async () => {
  // 键盘事件处理
  document.addEventListener("keydown", e => {
    if (e.key === "Escape") {
      closeAddCategoryModal();
      closeAddValueModal();
      closeEditModal();
    }
  });
  let res = await getDictList({ dict_type: "类目" });
  productSpecs.value = res.data.list;
  console.log(productSpecs.value.length);
});

// 监听模态框状态变化，处理动画
watch(addCategoryModalVisible, newVal => {
  if (newVal) {
    setTimeout(() => {
      const modal = document.getElementById("add-category-modal");
      if (modal) {
        modal.querySelector("div").classList.add("scale-100");
        modal.querySelector("div").classList.remove("scale-95");
      }
    }, 10);
  }
});

watch(addValueModalVisible, newVal => {
  if (newVal) {
    setTimeout(() => {
      const modal = document.getElementById("add-value-modal");
      if (modal) {
        modal.querySelector("div").classList.add("scale-100");
        modal.querySelector("div").classList.remove("scale-95");
      }
    }, 10);
  }
});

watch(editValueModalVisible, newVal => {
  if (newVal) {
    setTimeout(() => {
      const modal = document.getElementById("edit-value-modal");
      if (modal) {
        modal.querySelector("div").classList.add("scale-100");
        modal.querySelector("div").classList.remove("scale-95");
      }
    }, 10);
  }
});
</script>

<style scoped>
.option-btn {
  @apply px-3 py-1.5 rounded-full bg-neutral-100 text-neutral-700 font-medium text-sm mr-2 mb-2 inline-flex items-center transition-all;
}
.option-btn:hover {
  @apply bg-neutral-200;
}
.option-btn.active {
  @apply bg-primary/10 text-primary;
}
.option-btn .delete-btn {
  @apply ml-2 opacity-0 transition-opacity;
}
.option-btn:hover .delete-btn {
  @apply opacity-100;
}
.content-auto {
  content-visibility: auto;
}
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}
.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
.transition-bg {
  transition: background-color 0.2s ease;
}
.transition-transform {
  transition: transform 0.2s ease;
}
.scale-hover {
  transition:
    transform 0.2s ease,
    box-shadow 0.2s ease;
}
.scale-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.option-btn {
  @apply px-3 py-1.5 rounded-full bg-neutral-100 text-neutral-700 font-medium text-sm mr-2 mb-2 inline-flex items-center transition-all;
}
.option-btn:hover {
  @apply bg-neutral-200;
}
.option-btn.active {
  @apply bg-primary/10 text-primary;
}
.option-btn .delete-btn {
  @apply ml-2 opacity-0 transition-opacity;
}
.option-btn:hover .delete-btn {
  @apply opacity-100;
}
.add-option-btn {
  @apply px-3 py-1.5 rounded-full border-2 border-dashed border-neutral-300 text-neutral-500 text-sm inline-flex items-center hover:border-primary hover:text-primary transition-all;
}
</style>
